package sublinear.common;

import java.util.Random;


/**
 * Utility class for pseudo-random number generation
 * Wraps Java built-in Random class, using a seed based on the system time
 * and a few utility classes 
 * 
 * @author itay
 *
 */
public class SimplePRNG {
	
	static SimplePRNG instance = null;

	public static SimplePRNG getInstance() {
		if (instance == null) {
			instance = new SimplePRNG();
		}
		return instance;
	}
	
	private SimplePRNG() {
		initialize();
	}
	
	private void initialize() {
		rand = new Random(System.currentTimeMillis());
	}
	
	public long nextLong(long n) {
		// Based on: http://stackoverflow.com/a/2546186/397604
		// A simple implementation for getting a long value within a range
		
		// error checking and 2^x checking removed for simplicity.
		long bits, val;
		do {
			bits = (rand.nextLong() << 1) >>> 1;
			val = bits % n;
		} while (bits-val+(n-1) < 0L);
		return val;
	}
	
	public int nextInt(int n) {
		return rand.nextInt(n);
	}
	
	
	public int flipUnbiasedCoin(){
		return rand.nextInt(100) % 2;
	}
		
	private Random rand = null;

}
